<template>
  <div class="card" style="width: 50%">
    <div style="font-size: 16px;">修改密码</div>
    <el-form ref="formRef" :rules="data.rules"  :model="data.user" label-width="80px" style="padding: 20px 30px 10px 0">
      <el-form-item prop="password" label="原密码" >
        <el-input show-password prefix-icon="Lock" v-model="data.user.password" autocomplete="off" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item prop="newPassword" label="新密码" >
        <el-input show-password prefix-icon="Lock" v-model="data.user.newPassword" autocomplete="off" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item prop="new2Password" label="确认密码" >
        <el-input show-password prefix-icon="Lock" v-model="data.user.new2Password" autocomplete="off" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePassword">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import {reactive, ref} from 'vue'
import request from "@/utils/request.js";
//  数据定义
const formRef = ref()
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || '{}'),
  rules:{
    newPassword: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
    new2Password: [
      { required: true, message: '请输入确认密码', trigger: 'blur' },
      { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
    ],
  }
})
const updatePassword = ()=>{
  formRef.value.validate((valid) => {
    if (valid) {
      request.post("/updatePassword", data.user).then(res => {
        if (res.code === '200') {
          ElMessage.success('更新成功')
          //延时跳转
          setInterval(()=>{
            localStorage.removeItem('code_user')
            location.href = '/login'
          }, 500)

        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
</script>
<style scoped>

</style>